package com.dmgis.qxfw.dataservice.businessservice.common.util;

//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.fastjson.JSONArray;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

public class JsonUtils {
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    /**
     * 将jsonobject转换相应的bean
     * @author : liukai 2017年7月20日 上午9:40:39
     * @param jsonObject
     * @param cls
     * @return
     * @throws JsonTobeanException
     */
    public static <T> T jsonTobean(JSONObject jsonObject, Class<T> cls) throws JsonTobeanException{
        if(jsonObject == null || jsonObject.size() == 0)return null;
        String methodName = null;
        Object obj = null;
        try {
            Method[] methods = cls.getDeclaredMethods();
            if( null != methods){
                for (Method method : methods) {
                    methodName = method.getName();
                    if(!methodName.startsWith("set"))continue;
                    //获取到属性的名称
                    methodName = methodName.substring(3,4).toLowerCase() + methodName.substring(4);
                    Map<String, Object> map = jsonObject;
                    Object value = map.get(methodName);
                    if(value!=null&& StringUtils.isNotBlank(value.toString().trim())
                            && !methodName.equalsIgnoreCase("class")&&
                            !value.toString().equals("null")){
                        if(obj == null)obj = cls.newInstance();
                        Class<?> paramType = method.getParameterTypes()[0];
                        if(paramType.getName().equals("java.util.Date")){
                            //时间类型
                            method.invoke(obj, sdf.parse(getTime(value.toString())));
                        }else if(paramType.getName().equals("java.sql.Timestamp")){
                            method.invoke(obj, Timestamp.valueOf(value.toString()));
                        }else if(paramType.getName().equals("java.math.BigDecimal")){
                            method.invoke(obj, new BigDecimal(value.toString()));
                        }else if(paramType.getName().equals("java.lang.Integer")){
                            method.invoke(obj, Integer.valueOf(value.toString()));
                        }else if(paramType.getName().equals("java.lang.Short")){
                            method.invoke(obj, Short.decode(value.toString()));
                        }else if(paramType.getName().equals("java.lang.Double")){
                            method.invoke(obj, Double.valueOf(value.toString()));
                        }else{
                            method.invoke(obj, value);
                        }
                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            //if(e instanceof NumberFormatException || e instanceof IllegalArgumentException){
            throw new JsonTobeanException(methodName);
            //}
            //NumberFormatException  IllegalArgumentException
        }
        return  (T) obj;
    }
    /**
     * 把毫秒转换成年月日
     *
     * @param time
     * @return
     */
    public static String getTime(String time) {
        if (time != null && !"".equals(time)) {
            if (time.contains("-")) {
                return time;
            } else {
                return sdf.format(new Date(Long.parseLong(time)));
            }
        } else {
            return "";
        }
    }

    /**
     * 将json转成相应的list
     * @author : liukai 2017年7月20日 上午9:41:16
     * @param json
     * @param cls
     * @return
     * @throws JsonTobeanException
     */
    public static <T> List<T> jsonToList(JSONArray json, Class<T> cls) throws JsonTobeanException{
        if(json == null)return null;
        List<T> result = new ArrayList<>();
        String key = null;
        try {
            Map<String, Method> map = new HashMap<>();
            Method[] methods = cls.getMethods();
            for (Method method : methods) {
                String methodName = method.getName().toLowerCase();
                if (methodName.startsWith("set")) {
                    map.put(methodName.substring(3), method);
                }
            }
            List<Map<String, Object>> list = (List<Map<String, Object>>) JSONArray.toCollection(json,Map.class);
            for (Map<String, Object> data : list) {
                Object obj = cls.newInstance();
                Iterator<Map.Entry<String, Method>> iterator = map.entrySet().iterator();
                while(iterator.hasNext()){
                    Map.Entry<String, Method> entry = iterator.next();
                    key = entry.getKey();
                    Object value = data.get(key);
                    if(value != null && StringUtils.isNotEmpty(value.toString())
                            &&!value.toString().equals("null")){
                        if(obj == null)obj = cls.newInstance();
                        Method method = entry.getValue();
                        Class<?> paramType = method.getParameterTypes()[0];
                        if(paramType==Integer.class){
                            method.invoke(obj, Integer.parseInt(value.toString()));
                        }else if(paramType == Date.class){
                            method.invoke(obj, sdf.parse(value.toString()));
                        }else if(paramType == BigDecimal.class){
                            method.invoke(obj, new BigDecimal(value.toString()));
                        }else if(paramType == Short.class){
                            method.invoke(obj, Short.decode(value.toString()));
                        }else if(paramType == Double.class){
                            method.invoke(obj, Double.parseDouble(value.toString()));
                        }else{
                            method.invoke(obj, value);
                        }
                    }
                }
                if(obj != null){
                    result.add((T) obj);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            if(e instanceof NumberFormatException || e instanceof IllegalArgumentException){
                throw new JsonTobeanException(key);
            }
        }
        return result;
    }
    public static void objWybhToUpdateFlag(List<Object> list){
        if(list != null&&list.size() != 0){
            for (Object object : list) {
                Class cls = object.getClass();
                Field[] fields = cls.getFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    String fieldName = field.getName();
                    if(fieldName.endsWith("10"));
                }
            }
        }
    }
    /**
     * 自定义异常 用于json转换时字段对应不上
     * @ClassName:JsonTobeanException
     * @author liukai email:179162890@qq.com
     * @date 2017年7月20日 上午9:46:06
     */
    public static class JsonTobeanException extends BusinessException{

        public JsonTobeanException(String msg) {
            super(msg);
            // TODO Auto-generated constructor stub
        }

    }
}
